package com.wfyvv.fast.common.core.valid;

import com.wfyvv.fast.common.core.ServiceException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * 校验工具类
 *
 * @author fengyu.wang
 * @since 2017-12-23 22:13:54
 */
public class ValidatorUtil {
    private ValidatorUtil() {
        throw new IllegalStateException("Utility class");
    }

    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param entity 待校验对象
     * @param group  待校验的组
     * @throws ServiceException 运行时异常
     */
    public static void validateEntity(Object entity, Class<?>... group) throws ServiceException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(entity, group);
        if (!constraintViolations.isEmpty()) {
            String msg = constraintViolations.stream()
                    .map(ConstraintViolation::getMessage)
                    .reduce("", (x, y) -> x.concat(y).concat("<br>"));
            throw new ServiceException(msg);
        }
    }
}
